<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" v-if="formShow">
          <template #Platform>
            <SelectPlatformSiteShop multiple class="lp-SelectPlatformSiteShop" :showRule="[true, false, false]" v-model:platform="form.platform_id" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VButton type="primary" @click="add" v-hasPermi="[basicSetupAuthList.commission_seting_otto.add]">
          <div class="dk-iconfont icon-Plus"></div>
          新增
        </VButton>
        <VButton type="primary" @click="batchOperation('batchEdit')" v-hasPermi="[basicSetupAuthList.commission_seting_otto.edit]"> 批量修改 </VButton>

        <VButton @click="handleStatus(1)" v-hasPermi="[basicSetupAuthList.commission_seting_otto.enable]">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]"></div>
           启用
        </VButton>
        <VButton @click="handleStatus(0)" v-hasPermi="[basicSetupAuthList.commission_seting_otto.disable]">
          <div class="dk-iconfont icon-Disabled text-[red]"></div>
          禁用
        </VButton>

        <div class="ml-auto">
          <VButton type="" @click="importHandleClick" v-hasPermi="[basicSetupAuthList.commission_seting_otto.export]">
            <div class="dk-iconfont icon-Upload"></div>
              导出
          </VButton>
        </div>
      </template>
    </VTable>

    <!-- 弹窗 表单编辑 -->
    <ConfirmInpuForm v-model="batchVisible" v-bind="getCurrentConfirm" @submit="handleConfirmSubmit" />

    <!-- 日志/ -->
    <Log dialog v-model="logVisible" :autoLoad="false" tag="order_channel_sku_commission" :business_id="logId" />

    <Vedit ref="edit" :title="editTitle" class="dialogPublic" @confirm="editConfirm"> </Vedit>

    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>
<script setup lang="jsx" name="basic-setupCommission-seting">
import { overallOptions } from "@/api/public"
import Vedit from "./components/edit"
import { queryList, commissionDelete, commissionStatus, commissionRate } from "./api"

import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"
import SelectPlatformSiteShop from "@/components/Selects/SelectPlatformSiteShop/index.vue"

import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"
import { basicSetupAuthList } from "@/Auth/basic-setup.js"

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = tableRef.value.getQueryForm()
  condition = initForm(condition)
  DerivedCenterRef.value.open({
    tag_name: "order_channel_sku_commission",
    condition,
  })
}

import ConfirmInpuForm from "@/components/ConfirmInpuForm/index.vue"
const batchVisible = ref(false)
const getCurrentConfirm = ref({})
// 保存 弹窗 表单编辑
const handleConfirmSubmit = async (param) => {
  console.log(param)
  let res = {}
  switch (getCurrentConfirm.value.type) {
    case "batchEdit":
      res = await commissionRate(param)
      break
  }
  ElMessage.success(res.message)
  getCurrentConfirm.value = {}
  batchVisible.value = false
  query()
}
// 开启 弹窗 表单编辑
const openConfirmInput = (type, params) => {
  let confirm = {}
  switch (type) {
    case "batchEdit":
      confirm = currentConfirmOpt.batchEdit
      confirm.length = params.id.length
      confirm.form = { ...params }
      break
    default:
      break
  }
  confirm.type = type
  console.log(confirm)

  getCurrentConfirm.value = confirm
  batchVisible.value = true
}
const currentConfirmOpt = {
  // 批量修改
  batchEdit: {
    title: "批量修改",
    formOptions: { labelWidth: "120px" },
    form: {},
    length: 0,
    fieldOptions: [
      { field: "commission_rate", label: "佣金比例(%)", style: { width: "300px" } },
      { field: "remark", label: "备注", type: "textarea", autosize: { minRows: 2, maxRows: 6 }, style: { width: "300px" } },
    ],
    rules: {
      commission_rate: [{ required: true, message: "请输入佣金比例", trigger: "blur" }],
    },
    tips: "根据已选中的数据进行修改；如果未录入数据则不修改选中记录的数据",
  },
}
const batchOperation = (type) => {
  const arr = getSelectRow()
  if (arr.length) {
    openConfirmInput(type, { id: arr })
  }
}

import XForm from "@/components/XForm/index.vue"
const form = ref()
const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  {
    field: "dateRange",
    type: "dateTimeRangeNorm",
    select: [
      { label: "创建时间", value: "create_time" },
      { label: "更新时间", value: "update_time" },
    ],
    selectStyle: { width: "100px" },
  },

  {
    field: "platform_id",
    slot: "Platform",
  },

  {
    field: "channel_sku_category",
    placeholder: "产品类目",
    type: "textarea",
    ...publicStyle,
  },
  {
    field: "status",
    type: "select",
    options: {
      placeholder: "状态",
      data: [
        { label: "启用", value: "1" },
        { label: "禁用", value: "0" },
      ],
    },
    style: { width: "100px" },
  },
])
const edit = ref()
const data = reactive({
  editTitle: "新增",
  statusOption: [],
})
const { editTitle, statusOption } = toRefs(data)
const tableRef = ref()

// 日志
import Log from "@/components/Log/index.vue"
const logRef = ref()
const logVisible = ref(false)
const logId = ref("")
const openLog = (row) => {
  logId.value = row.id
  logVisible.value = true
}

//编辑
const ruleEdit = (row) => {
  editTitle.value = "编辑"
  edit.value.open(row)
}

//新增
const add = () => {
  editTitle.value = "新增"
  edit.value.open()
}
const editConfirm = () => {
  query()
}
//删除
const profitSettingDeleteF = (id) => {
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      commissionDelete({ id }).then((res) => {
        ElMessage({ message: "删除成功！", type: "success" })
        query()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}

//启用
const handleStatus = (status) => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  commissionStatus({ id: arr, status }).then((res) => {
    ElMessage({ message: "操作成功", type: "success" })
    query()
  })
}

// 查询
const query = () => {
  tableRef?.value.query()
}
const formShow = ref(false)
//获取下拉数据
onMounted(() => {
  overallOptions({ params: ["base.orderCommission"] }).then((res) => {
    statusOption.value = res.data.baseOrderCommission.status
  })
  setTimeout(() => {
    formShow.value = true
  }, 10)
})
//获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "create_time", value: [] },
    },
  },
  showOverflow: true,
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },
    { field: "id", title: "ID", width: 80 },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={row.status == 1} />,
      },
    },

    { field: "platform_id_desc", title: "平台", width: 100 },
    { field: "channel_sku_category", title: "类目/产品类目", minWidth: 150 },
    { field: "currency", title: "币种", width: 100 },
    { field: "lowest_selling_price", title: "最低金额", width: 100 },
    { field: "highest_selling_price", title: "最高金额", width: 100 },
    { field: "commission_rate", title: " 佣金比例(%)", width: 100 },
    { field: "remark", title: "备注", width: 150 },
    { field: "create_user", title: "创建人", width: 100 },
    { field: "create_time", title: "创建时间", width: 150 },
    { field: "create_user", title: "修改人", width: 100 },
    { field: "update_time", title: "修改时间", width: 150 },

    {
      title: "操作",
      width: 150,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => ruleEdit(row)} v-hasPermi={[[basicSetupAuthList.commission_seting_otto.edit]]}>
                编辑
              </el-button>
              <el-button link type="primary" onClick={() => openLog(row)} v-hasPermi={[[basicSetupAuthList.commission_seting_otto.log]]}>
                日志
              </el-button>
              <el-button link type="danger" onClick={() => profitSettingDeleteF(row.id)} v-hasPermi={[[basicSetupAuthList.commission_seting_otto.delete]]}>
                删除
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let params = { ...initForm(form), ...page }

        return queryList(params)
      },
    },
  },
})
const initForm = (form) => {
  form.channel_sku_category = form.channel_sku_category?.split?.("\n").filter(Boolean)
  form.channel_sku_category = form.channel_sku_category?.map((v) => v?.trim())
  return form
}
</script>
<style lang="scss" scoped></style>
